﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

namespace Server
{
    class ServerModel
    {
        private ServerPPTControl PPT;
        private ServerBluetooth BT;
        private ServerForm UI;

        public ServerModel(ServerForm ui)
        {
            UI = ui;
        }

        public void initialization(string filePath)
        {
            PPT = new ServerPPTControl(filePath);
            PPT.setSlideShowBeginEventHandler(this.dealShowBeginEvent);
            PPT.setSlideShowNextSlideEventHandler(this.dealNextSlideEvent);
            PPT.setSlideShowEndEventHandler(this.dealShowEndEvent);

            BT = new ServerBluetooth();
            BT.setGetMessageEventHandler(dealGetMessage);
          
        }

        public void startBluetooth()
        {
            if (BT.start())
            {
                UI.setLabel("服务器开启成功");
            }
            else
            {
                UI.setLabel("本地蓝牙设备错误");
                close();
            }
        }

        private void dealGetMessage(object sender, ServerBluetooth.GetMessageEventArgs e)
        {
            if (e.message.behest == ServerMessage.START)
            {
                PPT.start();
            }
            else if (e.message.behest == ServerMessage.NEXT)
            {
                PPT.next();
            }
            else if (e.message.behest == ServerMessage.PREVIOUS)
            {
                PPT.previous();
            }
            else if (e.message.behest == ServerMessage.CLOSE)
            {
                UI.setLabel("与客户端断开连接,请重新启动服务端与客户端");
                close();
            }
        }

        private void dealShowBeginEvent(PowerPoint.SlideShowWindow Wn)
        {
            PPT.SlidesCount = Wn.Presentation.Slides.Count;
            BT.sengMessage(new ServerMessage(ServerMessage.HEAD_SHOWBEGIN, (byte)PPT.SlidesCount));
            //隐藏窗体
            //UI.Visible = false;
        }

        private void dealNextSlideEvent(PowerPoint.SlideShowWindow Wn)
        {
            PPT.ShowPosition = Wn.View.CurrentShowPosition;
            BT.sengMessage(new ServerMessage(ServerMessage.HEAD_SHOWING, (byte)PPT.ShowPosition));
        }

        private void dealShowEndEvent(PowerPoint.Presentation Pres)
        {
            BT.sengMessage(new ServerMessage(ServerMessage.HEAD_SHOWEND, 0));
            //显示窗体
            //UI.Visible = true;
            UI.setLabel("放映结束");
        }

        public void close()
        {
            if (BT != null)
            {
                BT.close();
                BT = null;
            }
            if (PPT != null)
            {
                PPT.close();
                PPT = null;
            }
        }
    }
}
